import { createRouter,createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { usePermissStore } from '../store/permiss'

const routes =[
    {
    path:'/',
    redirect:'/dashboard',
    },
    {
        path:'/',
        name:'Home',
        component: Home,
        children:[
            {
                path:'/dashboard',
                name:'dashboard',
                meta:{
                    title:'系统首页',
                    noAuth:true,
                },
                component: ()=>import('../views/dashboard.vue')
            },
            {
                path:'/system-user',
                name:'system-user',
                meta:{
                    title:'用户管理',
                    permiss:'11'
                },
                component: ()=>import('../views/system-user.vue')
            },
            {
                path:'/system-role',
                name:'system-role',
                meta:{
                    title:'角色管理',
                    permiss:'12'
                },
                component: ()=>import('../views/system-role.vue')
            }
        ]
    },
    {
        path:'/login',
        meta:{
            title:'登录',
            noAuth:true
        },
        component: ()=>import('../views/Login.vue')
    },
    {
        path:'/403',
        meta:{
            title:'403',
            noAuth:true
        },
        component: ()=>import('../views/403.vue')
    },
    {
        path:'/404',
        meta:{
            title:'404',
            noAuth:true
        },
        component: ()=>import('../views/404.vue')
    },
    {
        // 动态匹配，接收除上面的url以外的
        path:'/:path(.*)', //.代表模糊匹配 
        redirect:'/404'

    }

]
// url 传统url 和后端一样
// 自己人用的，浏览器不支持的话可以换，无所谓 
const router = createRouter({
    history: createWebHistory(),
    routes
})

router.beforeEach((to,from,next)=>{

    NProgress.start()  // 开始进度条
    document.title = to.meta.title //更改页面名称 这个一定要有
    const role = localStorage.getItem('ms_name');
    const permissStore =  usePermissStore();

    if( !role && to.meta.noAuth !== true){
        next('/login')
    }else if(typeof to.meta.permiss  == 'String' 
        && !permissStore.key.includes(to.meta.permiss)){
        next('/403')
    }else{
        next() // 不需要登录或者登录了有相应的权限的页面
    }
})

router.afterEach(()=>{
    NProgress.done()  // 结束进度条
})


export default router;